package com.func.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.func.domain.award.event.SendAwardMessageEvent;
import com.func.domain.award.model.entity.DistributeAwardEntity;
import com.func.domain.award.service.IAwardService;
import com.func.types.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * SendAwardCustomer
 * </p>
 *
 * @author Simon
 * @version 2025.03.16.1.0.0
 * @description
 * @since 2025-03-16
 */

@Slf4j
@Component
public class SendAwardCustomer {

    @Value("${spring.rabbitmq.topic.send_award}")
    private String topic;

    @Resource
    private IAwardService awardService;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_award}"))
    public void listener(String message) {
        try {
            log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message);
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            }.getType() );
            SendAwardMessageEvent.SendAwardMessage sendAwardMessage = eventMessage.getData();

            // 发放奖品
            awardService.distributeAward(DistributeAwardEntity.builder()
                    .awardId(sendAwardMessage.getAwardId())
                    .awardConfig(sendAwardMessage.getAwardConfig())
                    .orderId(sendAwardMessage.getOrderId())
                    .userId(sendAwardMessage.getUseId())
                    .build()
            );
        } catch (Exception e) {
            log.error("监听用户奖品发送消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }
}
